package org.androidpush.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import org.androidpush.R;
import org.androidpush.greendao.UserFriend;
import org.androidpush.model.UserDto;

public class SortLinkAdapter extends BaseAdapter {
	private Context context;
	private List<UserFriend> friendDatas;
	private LayoutInflater inflater;

	public SortLinkAdapter(Context context, List<UserFriend> friendDatas) {
		this.context = context;
		this.friendDatas = friendDatas;
		this.inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return friendDatas.size();
	}

	@Override
	public Object getItem(int position) {
		return friendDatas.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewholder = null;
		UserFriend friend = friendDatas.get(position);
		if (convertView == null) {
			viewholder = new ViewHolder();
			convertView = inflater.inflate(R.layout.xml_link_item, null);
			viewholder.tv_tag = (TextView) convertView
					.findViewById(R.id.id_linkitem_tag);
			viewholder.tv_name = (TextView) convertView
					.findViewById(R.id.id_linkitem_name);
			viewholder.img_name = (ImageView)convertView.findViewById(R.id.id_linkitem_img);
			viewholder.tv_msg = (TextView)convertView.findViewById(R.id.id_linkitem_msgCount);
			convertView.setTag(viewholder);
		} else {
			viewholder = (ViewHolder) convertView.getTag();
		}
		int selection = friend.getFirstPinYin().charAt(0);

		int positionForSelection = getPositionForSelection(selection);
		if (position == positionForSelection) {
			viewholder.tv_tag.setVisibility(View.VISIBLE);
			viewholder.tv_tag.setText(friend.getFirstPinYin());
		} else {
			viewholder.tv_tag.setVisibility(View.GONE);
		}
		viewholder.tv_name.setText(friend.getFriendName());
		viewholder.img_name.setImageDrawable(convertView.getResources().getDrawable(friend.getFriendImg()));
		if(friend.getNewMsgCount()!=null){
			viewholder.tv_msg.setText(friend.getNewMsgCount());
			viewholder.tv_msg.setVisibility(View.VISIBLE);
		}else {
			viewholder.tv_msg.setVisibility(View.GONE);
		}
		return convertView;
	}

	public int getPositionForSelection(int selection) {
		for (int i = 0; i < friendDatas.size(); i++) {
			String Fpinyin = friendDatas.get(i).getFirstPinYin();
			char first = Fpinyin.toUpperCase().charAt(0);
			if (first == selection) {
				return i;
			}
		}
		return -1;
	}

	class ViewHolder {
		TextView tv_tag,tv_name,tv_msg;
		ImageView img_name;
	}
}
